package com.jeehentor.ai.config;

import com.jeehentor.ai.core.*;
import com.jeehentor.ai.entity.AiPlatformConfig;
import com.jeehentor.ai.mapper.AiPlatformConfigMapper;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * 动态调度器（工厂）
 */
@Service
@RequiredArgsConstructor
public class AiClientManager {

    private final AiPlatformConfigMapper configMapper;
    private final AiSessionManager sessionManager;

    private final Map<String, Function<AiPlatformConfig, AiClient>> registry = new HashMap<>();

    @PostConstruct
    public void registerClients() {
        registry.put("deepseek", config -> new DeepSeekClient(config, sessionManager));
        registry.put("doubao", config -> new DoubaoClient(config, sessionManager));
    }

    public AiClient getClient(String platform) {
        AiPlatformConfig config = configMapper.selectByPlatformName(platform)
                .orElseThrow(() -> new IllegalArgumentException("未找到可用配置：" + platform));

        Function<AiPlatformConfig, AiClient> builder = registry.get(config.getPlatform().toLowerCase());
        if (builder == null) throw new UnsupportedOperationException("不支持的平台：" + config.getPlatform());

        return builder.apply(config);
    }

    public boolean isStream(String platform) {
        return configMapper.selectByPlatformName(platform)
                .map(AiPlatformConfig::getIsStream)
                .orElse(false);
    }
}

